package com.east.controller.system;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.east.bean.Privilege;
import com.east.bean.Role;
import com.east.bean.User;
import com.east.service.system.LoginService;
import com.east.utils.Result;
import com.east.utils.ResultUtil;

@RestController
@RequestMapping("login")
public class LoginController {
	@Autowired
	LoginService loginService;
	/*@GetMapping("")
	public Result Login(String account,String pwd) {
		User findByLogin = loginService.findByLogin(account, pwd);
		return ResultUtil.success(findByLogin);
	}*/
	@GetMapping("role")
	public Result Login(Integer id) {
		List<Role> findByRolePrivile = loginService.findByRolePrivile(id);
		return ResultUtil.success(findByRolePrivile);
	}
	@GetMapping("")
    public Result submitLogin(String username, String password, HttpServletRequest request) {
			
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            String user =  (String)subject.getPrincipal();
            byte[] decodeBase64 = Base64.decodeBase64(user);
	        String string=null;
			try {
				string = new String(decodeBase64,"UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			User stu = JSON.parseObject(string,new TypeReference<User>() {});
            Session session = subject.getSession();
            HashMap<String, Object> hashMap = new HashMap<String,Object>();
           
            hashMap.put("user", stu);
            hashMap.put("Authorization", session.getId());
        // 执行到这里说明用户已登录成功
        return ResultUtil.success(hashMap);
    }
	@GetMapping("exit")
    public Result submitexit(String username, String password, HttpServletRequest request) {
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
        // 执行到这里说明用户已登录成功
        return ResultUtil.success(null);
    }
}
